package cn.actoncode.boot.module.ai.controller.app.intelligentagent;

import cn.actoncode.boot.framework.common.pojo.CommonResult;
import cn.actoncode.boot.framework.security.core.annotations.PreAuthenticated;
import cn.actoncode.boot.framework.web.core.util.WebFrameworkUtils;
import cn.actoncode.boot.module.ai.controller.app.intelligentagent.vo.*;
import cn.actoncode.boot.module.ai.convert.intelligentagent.ChatRecordConvert;
import cn.actoncode.boot.module.ai.convert.intelligentagent.IntelligentAgentConvert;
import cn.actoncode.boot.module.ai.dal.dataobject.chat.ChatRecordDO;
import cn.actoncode.boot.module.ai.dal.dataobject.intelligentagent.IntelligentAgentDO;
import cn.actoncode.boot.module.ai.service.chat.ChatRecordService;
import cn.actoncode.boot.module.ai.service.intelligentagent.IntelligentAgentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static cn.actoncode.boot.framework.common.pojo.CommonResult.success;

@Tag(name = "智能体 API")
@RestController
@RequestMapping("/ia")
@Validated
@Slf4j
public class IntelligentAgentController {

	@Resource
	private IntelligentAgentService intelligentAgentService;

	@Resource
	private ChatRecordService chatRecordService;

	@PostMapping("/chat")
	@Operation(summary = "聊天")
	@PreAuthenticated
	public CommonResult<IntelligentAgentChatRespVO> chat(@Valid @RequestBody IntelligentAgentChatReqVO reqVO) {
		return success(intelligentAgentService.chat(reqVO));
	}

	@GetMapping("/chat-list")
	@Operation(summary = "聊天记录")
	@PreAuthenticated
	public CommonResult<List<ChatRecordResp>> getChatRecordList() {
		Long userId = WebFrameworkUtils.getLoginUserId();
		List<ChatRecordDO> chatRecordList = chatRecordService.getChatRecordList(userId);
		return success(ChatRecordConvert.INSTANCE.convertList(chatRecordList));
	}

	@GetMapping("/chat-clear")
	@Operation(summary = "清除聊天记录")
	@PreAuthenticated
	public CommonResult<Boolean> clearChat() {
		Long userId = WebFrameworkUtils.getLoginUserId();
		chatRecordService.clearChat(userId);
		return success(true);
	}

	@PostMapping("/used-ability")
	@Operation(summary = "使用能力")
	@PreAuthenticated
	public CommonResult<IntelligentAgentUsedAbilityRespVO> usedAbility(@Valid @RequestBody IntelligentAgentUsedAbilityReqVO reqVO) {
		return success(intelligentAgentService.usedAbility(reqVO));
	}

	@GetMapping("/get")
	@Operation(summary = "获取智能体")
	@PreAuthenticated
	public CommonResult<IntelligentAgentRespVO> getIntelligentAgent() {
		IntelligentAgentDO intelligentAgent = intelligentAgentService.getIntelligentAgent();
		return success(IntelligentAgentConvert.INSTANCE.convert(intelligentAgent));
	}
}
